//
//  TranslatorWordController.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/5/9.
//

import UIKit
import Reusable
import AVFoundation

extension TranslatorWordController: NibLoadable {}

class TranslatorWordController: BaseViewController {
    
    /// 翻译按钮
    @IBOutlet weak var translationButton: UIButton!
    
    @IBOutlet weak var inView: UIView!
    @IBOutlet weak var inTextView: UITextView!
    
    @IBOutlet weak var outView: UIView!
    @IBOutlet weak var outTextView: UITextView!
    
    @IBOutlet weak var outToolsView: UIView!
    @IBOutlet weak var copyView: UIView!
    @IBOutlet weak var playView: UIView!
    
    @IBOutlet weak var copyLabel: UILabel!
    @IBOutlet weak var playLabel: UILabel!
    
    @IBOutlet weak var leftView: UIView!
    @IBOutlet weak var leftImageView: UIImageView!
    @IBOutlet weak var leftLabel: UILabel!
    
    @IBOutlet weak var rightView: UIView!
    @IBOutlet weak var rightImageView: UIImageView!
    @IBOutlet weak var rightLabel: UILabel!
    
    private var isPlaying = false
    
    var from: LanguageTpye = .zh {
        didSet {
            if from == .zh {
                
                leftImageView.image = "ic_中国".toImage
                leftLabel.text = "中文".localized(.login)
                
                rightImageView.image = "ic_俄罗斯".toImage
                rightLabel.text = "俄语".localized(.login)
                
            } else {
                rightImageView.image = "ic_中国".toImage
                rightLabel.text = "中文".localized(.login)
                
                leftImageView.image = "ic_俄罗斯".toImage
                leftLabel.text = "俄语".localized(.login)
            }
            
            inTextView.text = ""
            cleanOut()
            
        }
    }
    
    let synthesizer = AVSpeechSynthesizer()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        synthesizer.delegate = self
        setupNav()
        setupUI()
        
        NotificationCenter.default.addObserver(self, selector: #selector(textViewTextDidChangeNotification), name: UITextView.textDidChangeNotification, object: inTextView)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        synthesizer.stopSpeaking(at: .immediate)
    }
    
    // 一键翻译
    @IBAction func translationAction(_ sender: Any) {
        if inTextView.text.isEmpty {
            YLHUD.showMessage("请输入需要翻译的文字".localized(.tran))
            return
        }
        
        // 翻译
        let from = self.from == .zh ? "zh": "ru"
        let to = self.from == .zh ? "ru": "zh"
        YLHUD.showLottie()
        NeoNuiTranslation.translation(from: from, to: to, text: inTextView.text) { sourceText, result in
            DispatchQueue.main.async { [self] in
                YLHUD.hideHUD()
                if let dst = result {
                    // 翻译结果 反显
                    outTextView.text = dst
                    
                    outView.backgroundColor = outTextView.text.count > 0 ? .clear: UIColor(hex: "F0F0F0")
                    outToolsView.isHidden = outTextView.text.isEmpty
                    
                } else {
                    YLHUD.showMessage("翻译失败")
                }
            }
        }
    }
    
    @IBAction func playAction(_ sender: Any) {
        // 使用示例
        if outTextView.text.isEmpty {
            return
        }
        speakTextWithDelay(text: outTextView.text)
    }
    
    @IBAction func copyAction(_ sender: Any) {
        if outTextView.text.isEmpty {
            return
        }
        let board = UIPasteboard.general
        board.string = outTextView.text
        YLHUD.showMessage("复制到剪切板".localized(.tran))
    }
    
    @IBAction func toggleLanguageAction(_ sender: UIButton) {
        from = (from == .zh ? .ru: .zh)
    }
    
    /// 更新语言
    override func updateLanguageAction() {
        navigationItem.title = "文字翻译".localized(.tran)
        translationButton.setTitle("一键翻译".localized(.tran), for: .normal)
        inTextView.placeholder = "请输入需要翻译的文字".localized(.tran)
        outTextView.placeholder = "翻译结果".localized(.tran)
        
        copyLabel.text = "复制".localized(.tran)
        playLabel.text = "朗读".localized(.tran)
        
    }
}

extension TranslatorWordController {
    func setupNav() {
        vhl_navBarBackgroundAlpha = 0
        navigationItem.title = "文字翻译".localized(.tran)
        
    }
    
    func setupUI() {
        translationButton.backgroundColor = .gradient(colors: [
            UIColor(hex: "#278AFF"),
            UIColor(hex: "#66D6E2")
        ], rect: CGRect(x: 0, y: 0, width: xScreenW - 24, height: 48))
        translationButton.addRoundedCorners(radius: 24)
        translationButton.setTitle("一键翻译".localized(.tran), for: .normal)
        
        inView.backgroundColor = .clear
        inView.addRoundedCorners(radius: 12, width: 1, color: .themeColor)
        inTextView.backgroundColor = .clear
        inTextView.text = ""
        inTextView.placeholder = "请输入需要翻译的文字".localized(.tran)
        inTextView.tintColor = .themeColor
        inTextView.returnKeyType = .done
        inTextView.delegate = self
        
        outView.backgroundColor = UIColor(hex: "F0F0F0")
        outView.addRoundedCorners(radius: 12, width: 1, color: .themeColor)
        
        outTextView.backgroundColor = .clear
        outTextView.text = ""
        outTextView.placeholder = "翻译结果".localized(.tran)
        outTextView.isEditable = false
        
        outToolsView.isHidden = true
        playView.addRoundedCorners(radius: 8)
        copyView.addRoundedCorners(radius: 8)
        copyLabel.text = "复制".localized(.tran)
        playLabel.text = "朗读".localized(.tran)
        
        leftView.addRoundedCorners(radius: 10, width: 1, color: .themeColor)
        rightView.addRoundedCorners(radius: 10, width: 1, color: .themeColor)
        from = .zh
        
        
    }
    
    func cleanOut() {
        outView.backgroundColor = UIColor(hex: "F0F0F0")
        outTextView.text = ""
        outToolsView.isHidden = true
    }
    
    @objc func textViewTextDidChangeNotification(noti: Notification) {
        let textField = noti.object as! UITextView
        if textField.text.isEmpty {
            cleanOut()
        }
    }
    
}
// MARK: - Action
extension TranslatorWordController {
    
    func speakTextWithDelay(text: String) {
        if isPlaying {
            YLHUD.showMessage("正在朗读中".localized(.tran))
            return
        }
        let utterance = AVSpeechUtterance(string: text)
        // 设置语言，例如使用英语（美国）en-US, 中文 zh-Hans
        let language = from == .zh ? "ru-RU": "zh-CN"
        utterance.voice = AVSpeechSynthesisVoice(language: language) // "zh-Hant-HK" 设置粤语
        // 设置语速 默认:0.5
        utterance.rate = AVSpeechUtteranceDefaultSpeechRate
        // 设置音调
        utterance.pitchMultiplier = 1.0
        // 设置音量
        utterance.volume = 1.0
        synthesizer.speak(utterance)
        
        let averageCharDuration: TimeInterval = 0.5 // 每个字符的平均朗读时间，单位为秒
        // 调整基于语速的朗读时间
        let totalDuration = TimeInterval(text.count) * averageCharDuration / Double(utterance.rate)
        // 播放文本并停顿2秒后停止
        DispatchQueue.main.asyncAfter(deadline: .now() + totalDuration) { [weak self] in
            xLog("停止")
            self?.synthesizer.stopSpeaking(at: .word)
        }
    }
    
}

extension TranslatorWordController: UITextViewDelegate {
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if text == "\n" {
            // 处理回车键按下的事件
            xLog("回车键被按下了")
            // 你可以在这里添加更多的逻辑，比如隐藏键盘等
            textView.resignFirstResponder() // 例如，隐藏键盘
            return false // 返回 false 表示不将换行符加入到 textView 中
        }
        return true // 对于其他文本更改，返回 true
    }

}


extension TranslatorWordController: AVSpeechSynthesizerDelegate {
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
        xLog("didFinish 播放完")
        let res = synthesizer.stopSpeaking(at: .immediate)
        xLog("停止 : \(res ? "ok": "no")")
        isPlaying = false
    }
    
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart utterance: AVSpeechUtterance) {
        xLog("didStart \(utterance)")
    }
    
    
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didCancel utterance: AVSpeechUtterance) {
        xLog("didCancel \(utterance)")
    }
}
